package com.roc.admin.infrastructure.repository.impl;

import com.roc.admin.domain.entity.LoginLog;
import com.roc.admin.domain.repository.LoginLogRepository;
import com.roc.admin.infrastructure.mapper.LoginLogMapper;
import com.roc.admin.infrastructure.persistence.LoginLogPO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

/**
 * 登录日志仓储实现类
 */
@Repository
public class LoginLogRepositoryImpl implements LoginLogRepository {

    private final LoginLogMapper loginLogMapper;

    public LoginLogRepositoryImpl(LoginLogMapper loginLogMapper) {
        this.loginLogMapper = loginLogMapper;
    }

    @Override
    public LoginLog save(LoginLog loginLog) {
        LoginLogPO loginLogPO = toLoginLogPO(loginLog);
        if (loginLogPO.getId() == null) {
            loginLogMapper.insert(loginLogPO);
        } else {
            loginLogMapper.updateById(loginLogPO);
        }
        return toLoginLog(loginLogPO);
    }

    /**
     * 将登录日志实体转换为持久化对象
     *
     * @param loginLog 登录日志实体
     * @return 登录日志持久化对象
     */
    private LoginLogPO toLoginLogPO(LoginLog loginLog) {
        if (loginLog == null) {
            return null;
        }
        LoginLogPO loginLogPO = new LoginLogPO();
        BeanUtils.copyProperties(loginLog, loginLogPO);
        return loginLogPO;
    }

    /**
     * 将持久化对象转换为登录日志实体
     *
     * @param loginLogPO 登录日志持久化对象
     * @return 登录日志实体
     */
    private LoginLog toLoginLog(LoginLogPO loginLogPO) {
        if (loginLogPO == null) {
            return null;
        }
        LoginLog loginLog = new LoginLog();
        BeanUtils.copyProperties(loginLogPO, loginLog);
        return loginLog;
    }
}
